using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Input;
using Microsoft.Win32;
using PatentAssistant.Services;
using PatentAssistant.Utils;
using System.Net.Http;
using System.Windows.Media;

namespace PatentAssistant.ViewModels
{
    public class MainViewModel : INotifyPropertyChanged
    {
        #region 属性

        private FlowDocument _mainDocument = new FlowDocument();
        public FlowDocument MainDocument
        {
            get => _mainDocument;
            set
            {
                _mainDocument = value;
                OnPropertyChanged();
            }
        }

        private bool _isBusy;
        public bool IsBusy
        {
            get => _isBusy;
            set
            {
                _isBusy = value;
                OnPropertyChanged();
                // 刷新命令可执行状态
                CommandManager.InvalidateRequerySuggested();
            }
        }

        private string _statusMessage = "就绪";
        public string StatusMessage
        {
            get => _statusMessage;
            set
            {
                _statusMessage = value;
                OnPropertyChanged();
            }
        }

        // AI连接状态相关属性
        private bool _isAIConnected = false;
        public bool IsAIConnected
        {
            get => _isAIConnected;
            set
            {
                _isAIConnected = value;
                OnPropertyChanged();
                OnPropertyChanged(nameof(AIConnectionStatus));
                OnPropertyChanged(nameof(AIConnectionColor));
                OnPropertyChanged(nameof(AIConnectionIcon));
            }
        }

        private DateTime? _lastConnectionTime;
        public DateTime? LastConnectionTime
        {
            get => _lastConnectionTime;
            set
            {
                _lastConnectionTime = value;
                OnPropertyChanged();
                OnPropertyChanged(nameof(LastConnectionText));
            }
        }

        private string _aiConnectionMessage = "未连接";
        public string AIConnectionMessage
        {
            get => _aiConnectionMessage;
            set
            {
                _aiConnectionMessage = value;
                OnPropertyChanged();
            }
        }

        // 计算属性
        public string AIConnectionStatus => IsAIConnected ? "已连接" : "未连接";
        public Brush AIConnectionColor => IsAIConnected ? Brushes.Green : Brushes.Red;
        public string AIConnectionIcon => IsAIConnected ? "✓" : "✗";
        public string LastConnectionText => LastConnectionTime?.ToString("HH:mm:ss") ?? "从未连接";

        #endregion

        #region 命令

        public ICommand GenerateCommand { get; }
        public ICommand PolishCommand { get; }
        public ICommand ContinueCommand { get; }
        public ICommand FormatCommand { get; }
        public ICommand ExportCommand { get; }
        public ICommand ClearCommand { get; }
        public ICommand TestAIConnectionCommand { get; }
        public ICommand AIConfigCommand { get; }
        public ICommand ExpandCommand { get; }
        public ICommand AboutCommand { get; }

        #endregion

        private readonly AIService _aiService = new AIService();
        private readonly HttpClient _httpClient = new HttpClient();

        // 委托用于与MainWindow通信
        public Func<string>? GetSelectedTextDelegate { get; set; }
        public Action<string>? ReplaceSelectedTextDelegate { get; set; }

        public MainViewModel()
        {
            // 初始化命令
            GenerateCommand = new RelayCommand(async _ => await GenerateDisclosure(), _ => !IsBusy);
            PolishCommand = new RelayCommand(async _ => await PolishSentences(), _ => !IsBusy && HasText());
            ContinueCommand = new RelayCommand(async _ => await ContinueWriting(), _ => !IsBusy && HasText());
            FormatCommand = new RelayCommand(async _ => await FormatText(), _ => !IsBusy && HasText());
            ExportCommand = new RelayCommand(_ => ExportDocx(), _ => !IsBusy && HasText());
            ClearCommand = new RelayCommand(_ => ClearText(), _ => !IsBusy && HasText());
            TestAIConnectionCommand = new RelayCommand(async _ => await TestAIConnection(), _ => !IsBusy);
            AIConfigCommand = new RelayCommand(_ => OpenAIConfig(), _ => !IsBusy);
            ExpandCommand = new RelayCommand(async _ => await ExpandText(), _ => !IsBusy && HasText());
            AboutCommand = new RelayCommand(_ => OpenAboutDialog(), _ => !IsBusy);
            
            // 添加初始提示
            TextUtils.SetText(MainDocument, "请在此输入专利技术资料，或者点击左侧功能按钮开始使用...");
            
            // 启动时测试AI连接
            _ = Task.Run(async () => await TestAIConnection());
        }

        #region 方法

        /// <summary>
        /// 测试AI连接状态
        /// </summary>
        private async Task TestAIConnection()
        {
            try
            {
                AIConnectionMessage = "正在测试连接...";
                
                // 简单的连接测试
                var testResult = await _aiService.CallAIAsync("测试连接", "test_connection");
                
                if (!testResult.Contains("API调用出错"))
                {
                    IsAIConnected = true;
                    LastConnectionTime = DateTime.Now;
                    AIConnectionMessage = "连接正常";
                    StatusMessage = "AI服务连接正常";
                }
                else
                {
                    IsAIConnected = false;
                    AIConnectionMessage = "连接失败";
                    StatusMessage = "AI服务连接失败";
                }
            }
            catch (Exception ex)
            {
                IsAIConnected = false;
                AIConnectionMessage = $"连接错误: {ex.Message}";
                StatusMessage = "AI服务连接异常";
            }
        }

        /// <summary>
        /// 打开AI配置对话框
        /// </summary>
        private void OpenAIConfig()
        {
            try
            {
                var configDialog = new AIConfigDialog(_aiService);
                configDialog.Owner = Application.Current.MainWindow;
                
                if (configDialog.ShowDialog() == true)
                {
                    // 配置已更新，重新测试连接
                    _ = Task.Run(async () => await TestAIConnection());
                    StatusMessage = "AI配置已更新";
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"打开配置对话框时出错: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 打开关于对话框
        /// </summary>
        private void OpenAboutDialog()
        {
            try
            {
                var aboutDialog = new AboutDialog();
                aboutDialog.Owner = Application.Current.MainWindow;
                aboutDialog.ShowDialog();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"打开关于对话框时出错: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 生成交底书
        /// </summary>
        private async Task GenerateDisclosure()
        {
            if (IsBusy) return;
            
            try
            {
                IsBusy = true;
                StatusMessage = "正在生成专利交底书...";
                
                string input = TextUtils.GetText(MainDocument);
                if (string.IsNullOrWhiteSpace(input) || input == "请在此输入专利技术资料，或者点击左侧功能按钮开始使用...")
                {
                    MessageBox.Show("请先输入技术资料！", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }
                
                string result = await _aiService.CallAIAsync(input, "generate_disclosure");
                result = TextUtils.RemoveChainContent(result);
                
                // 如果结果为空或只包含空白字符，提示用户
                if (string.IsNullOrWhiteSpace(result.Trim()))
                {
                    MessageBox.Show("AI未能生成有效的交底书内容，请检查输入内容或重试。", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }
                
                // 应用格式规整
                result = TextUtils.FormatText(result);
                
                TextUtils.SetText(MainDocument, result);
                StatusMessage = "交底书生成完成";
            }
            catch (Exception ex)
            {
                MessageBox.Show($"生成交底书时出错: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                StatusMessage = "生成失败";
            }
            finally
            {
                IsBusy = false;
            }
        }

        /// <summary>
        /// 逐句润色
        /// </summary>
        private async Task PolishSentences()
        {
            if (IsBusy) return;
            
            try
            {
                IsBusy = true;
                StatusMessage = "正在进行润色...";
                
                string selectedText = GetSelectedText();
                string fullText = TextUtils.GetText(MainDocument);
                
                // 如果没有选中文本，则对全文进行润色
                if (string.IsNullOrWhiteSpace(selectedText))
                {
                    if (string.IsNullOrWhiteSpace(fullText) || fullText == "请在此输入专利技术资料，或者点击左侧功能按钮开始使用...")
                    {
                        MessageBox.Show("请先输入要润色的内容！", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                        return;
                    }
                    
                    // 对全文进行润色
                    string polished = await _aiService.CallAIAsync(fullText, "polish_sentence");
                    polished = TextUtils.RemoveChainContent(polished);
                    
                    if (string.IsNullOrWhiteSpace(polished.Trim()))
                    {
                        MessageBox.Show("AI未能生成有效的润色结果，请重试。", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                        return;
                    }
                    
                    // 询问用户是否替换全文
                    var result = MessageBox.Show(
                        "是否用润色后的内容替换全文？", 
                        "全文润色确认", 
                        MessageBoxButton.YesNo, 
                        MessageBoxImage.Question);
                        
                    if (result == MessageBoxResult.Yes)
                    {
                        TextUtils.SetText(MainDocument, polished);
                        StatusMessage = "全文润色完成";
                    }
                    else
                    {
                        StatusMessage = "润色已取消";
                    }
                }
                else
                {
                    // 对选中的文本进行润色
                    string polished = await _aiService.CallAIAsync(selectedText, "polish_sentence");
                    polished = TextUtils.RemoveChainContent(polished);
                    
                    if (string.IsNullOrWhiteSpace(polished.Trim()))
                    {
                        MessageBox.Show("AI未能生成有效的润色结果，请重试。", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                        return;
                    }
                    
                    // 询问用户是否替换
                    var result = MessageBox.Show(
                        $"润色结果：\n\n{polished}\n\n是否替换原文？", 
                        "润色确认", 
                        MessageBoxButton.YesNo, 
                        MessageBoxImage.Question);
                        
                    if (result == MessageBoxResult.Yes)
                    {
                        ReplaceSelectedText(polished);
                        StatusMessage = "润色完成";
                    }
                    else
                    {
                        StatusMessage = "润色已取消";
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"润色时出错: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                StatusMessage = "润色失败";
            }
            finally
            {
                IsBusy = false;
            }
        }

        /// <summary>
        /// 获取选中的文本
        /// </summary>
        private string GetSelectedText()
        {
            return GetSelectedTextDelegate?.Invoke() ?? string.Empty;
        }

        /// <summary>
        /// 替换选中的文本
        /// </summary>
        private void ReplaceSelectedText(string newText)
        {
            ReplaceSelectedTextDelegate?.Invoke(newText);
        }

        /// <summary>
        /// 智能续写
        /// </summary>
        private async Task ContinueWriting()
        {
            if (IsBusy) return;
            
            try
            {
                IsBusy = true;
                StatusMessage = "正在续写...";
                
                string input = TextUtils.GetText(MainDocument);
                if (string.IsNullOrWhiteSpace(input) || input == "请在此输入专利技术资料，或者点击左侧功能按钮开始使用...")
                {
                    MessageBox.Show("请先输入要续写的内容！", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }
                
                string result = await _aiService.CallAIAsync(input, "continue_writing");
                
                // 过滤思维链内容
                result = TextUtils.RemoveChainContent(result);
                
                // 如果结果为空或只包含空白字符，提示用户
                if (string.IsNullOrWhiteSpace(result.Trim()))
                {
                    MessageBox.Show("AI未能生成有效的续写内容，请检查输入内容或重试。", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }
                
                // 追加文本到现有内容
                TextUtils.AppendText(MainDocument, "\n\n" + result);
                StatusMessage = "续写完成";
            }
            catch (Exception ex)
            {
                MessageBox.Show($"续写时出错: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                StatusMessage = "出错";
            }
            finally
            {
                IsBusy = false;
            }
        }

        /// <summary>
        /// 格式规整
        /// </summary>
        private async Task FormatText()
        {
            if (IsBusy) return;
            
            try
            {
                IsBusy = true;
                StatusMessage = "正在规整格式...";
                
                string input = TextUtils.GetText(MainDocument);
                if (string.IsNullOrWhiteSpace(input) || input == "请在此输入专利技术资料，或者点击左侧功能按钮开始使用...")
                {
                    MessageBox.Show("请先输入要规整的内容！", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }
                
                // 调用AI服务进行智能格式规整
                string result = await _aiService.CallAIAsync(input, "format_text");
                result = TextUtils.RemoveChainContent(result);
                
                // 如果结果为空或只包含空白字符，提示用户
                if (string.IsNullOrWhiteSpace(result.Trim()))
                {
                    MessageBox.Show("AI未能生成有效的规整结果，请检查输入内容或重试。", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }
                
                // 应用本地格式规整
                result = TextUtils.FormatText(result);
                
                TextUtils.SetText(MainDocument, result);
                StatusMessage = "格式规整完成";
            }
            catch (Exception ex)
            {
                MessageBox.Show($"格式规整时出错: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                StatusMessage = "规整失败";
            }
            finally
            {
                IsBusy = false;
            }
        }

        /// <summary>
        /// 扩写功能
        /// </summary>
        private async Task ExpandText()
        {
            if (IsBusy) return;
            
            try
            {
                IsBusy = true;
                StatusMessage = "正在扩写...";
                
                string selectedText = GetSelectedText();
                if (string.IsNullOrWhiteSpace(selectedText))
                {
                    MessageBox.Show("请先选中要扩写的段落！", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }
                
                // 对选中的文本进行扩写
                string expanded = await _aiService.CallAIAsync(selectedText, "expand_text");
                expanded = TextUtils.RemoveChainContent(expanded);
                
                if (string.IsNullOrWhiteSpace(expanded.Trim()))
                {
                    MessageBox.Show("AI未能生成有效的扩写结果，请重试。", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }
                
                // 询问用户是否替换
                var result = MessageBox.Show(
                    $"扩写结果：\n\n{expanded}\n\n是否替换原文？", 
                    "扩写确认", 
                    MessageBoxButton.YesNo, 
                    MessageBoxImage.Question);
                    
                if (result == MessageBoxResult.Yes)
                {
                    ReplaceSelectedText(expanded);
                    StatusMessage = "扩写完成";
                }
                else
                {
                    StatusMessage = "扩写已取消";
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"扩写时出错: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                StatusMessage = "扩写失败";
            }
            finally
            {
                IsBusy = false;
            }
        }

        /// <summary>
        /// 导出为.docx
        /// </summary>
        private void ExportDocx()
        {
            if (IsBusy) return;
            
            try
            {
                IsBusy = true;
                StatusMessage = "正在导出文档...";
                
                SaveFileDialog dlg = new SaveFileDialog 
                { 
                    Filter = "Word文档|*.docx",
                    Title = "导出为Word文档",
                    DefaultExt = ".docx",
                    AddExtension = true
                };
                
                if (dlg.ShowDialog() == true)
                {
                    DocxExporter.ExportFlowDocumentToDocx(MainDocument, dlg.FileName);
                    StatusMessage = "导出完成";
                    
                    // 询问是否打开文档
                    var result = MessageBox.Show(
                        "导出成功！是否立即打开文档？", 
                        "导出完成", 
                        MessageBoxButton.YesNo, 
                        MessageBoxImage.Question);
                        
                    if (result == MessageBoxResult.Yes)
                    {
                        try
                        {
                            // 使用更安全的方式打开文档
                            var psi = new System.Diagnostics.ProcessStartInfo
                            {
                                FileName = dlg.FileName,
                                UseShellExecute = true
                            };
                            System.Diagnostics.Process.Start(psi);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show($"无法打开文档: {ex.Message}\n文档已保存到: {dlg.FileName}", 
                                "打开失败", MessageBoxButton.OK, MessageBoxImage.Information);
                        }
                    }
                }
                else
                {
                    StatusMessage = "导出已取消";
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"导出时出错: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                StatusMessage = "导出失败";
            }
            finally
            {
                IsBusy = false;
            }
        }
        
        /// <summary>
        /// 清空文本
        /// </summary>
        private void ClearText()
        {
            if (MessageBox.Show(
                "确定要清空当前文本吗？", 
                "确认", 
                MessageBoxButton.YesNo, 
                MessageBoxImage.Question) == MessageBoxResult.Yes)
            {
                TextUtils.SetText(MainDocument, string.Empty);
                _aiService.ClearHistory();
            }
        }
        
        /// <summary>
        /// 检查是否有文本
        /// </summary>
        private bool HasText()
        {
            string text = TextUtils.GetText(MainDocument);
            return !string.IsNullOrWhiteSpace(text) && 
                   text != "请在此输入专利技术资料，或者点击左侧功能按钮开始使用...";
        }

        #endregion

        #region INotifyPropertyChanged

        public event PropertyChangedEventHandler? PropertyChanged;
        
        protected void OnPropertyChanged([CallerMemberName] string? name = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
        }

        #endregion
    }
} 